package com.liyuxiang.service.impl;

import com.liyuxiang.pojo.entity.LoginUser;
import com.liyuxiang.pojo.entity.User;
import com.liyuxiang.pojo.vo.BlogLoginVo;
import com.liyuxiang.pojo.vo.UserInfoVo;
import com.liyuxiang.service.BlogLoginService;
import com.liyuxiang.utils.BeanCopyUtils;
import com.liyuxiang.utils.JwtUtil;
import com.liyuxiang.utils.RedisCache;
import com.liyuxiang.vm.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate==null){
            System.out.println("用户名或密码错误");
        }
        //判断是否验证通过
        //获取用户id并生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long loginUserId = loginUser.getUser().getId();
        String token = JwtUtil.createJWT(loginUserId.toString());
        redisCache.setCacheObject("blogLogin" + loginUserId, loginUser);
        //把token和userinfo封装返回
        return new ResponseResult().ok(new BlogLoginVo(token, BeanCopyUtils.copyBean(loginUser.user, UserInfoVo.class)));
    }

    @Override
    public ResponseResult logout() {
        //从SecutiryContextHolder中获取token    这里可以直接获取token，因为如果没有token的话，过滤器会直接提示登录
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisCache.deleteObject("blogLogin"+loginUser.getUsername());
        return ResponseResult.okResult(null);
    }
}
